from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from project_1.settings import BASE_DIR
import json
# 主页
def index(request):
	# 定义个变量控制首页只显示四条数据
	cou = 1
	# 获取所以分类 一级
	cate = models.Cates.objects.filter(pid=0).exclude(isDelete=True)
	for i in cate:
		i.ad = models.Cates.objects.filter(pid=i.id).exclude(isDelete=True)

	return render(request,'myhome/index.html',{"cateData":cate})

# 封装加密密码函数
def getPwd(pwd):
	upass = make_password(pwd, None, 'pbkdf2_sha256')
	return upass

# 登录
def login(request):
	if request.method == "GET":
		global wan,pin
		pin = "?"
		paths = request.GET.get('paths','/myhome')
		if paths=="/myhome/login/" or paths=="/myhome/register/":
			paths = '/myhome'
		args = eval(request.GET.get('args','{}'))
		for i,j in args.items():
			pin+=i+"="+j+"&"
		wan = paths+pin[0:-1:]	
		print(wan,'---------------')
		return render(request,'myhome/login.html')
	else:
		# 验证验证码
		res = request.POST.dict()
		user = models.Users.objects.all()
		try:
			# 验证手机	
			ph = user.get(phone=res['phone'])
			if ph.status == 3:
					return HttpResponse("<script>alert('对不起！该账号已被禁用');location.href='"+reverse('myhome_login')+pin[0:-1]+"'</script>")
			# 密码验证
			flag = False
			for i in user:
				
				
				if check_password(res['password'],i.password):
					flag = True
					break
			if flag:
				request.session['vipUser'] = {"username":ph.username,"id":ph.id,"phone":ph.phone}
				return HttpResponse("<script>alert('登录成功');location.href='"+wan+"'</script>")
			else:
				return HttpResponse("<script>alert('手机与密码不匹配');location.href='"+reverse('myhome_login')+pin[0:-1]+"'</script>")
		except:
			return HttpResponse("<script>alert('手机不存在');location.href='"+reverse('myhome_login')+pin[0:-1]+"'</script>")
			
# 退出
def logout(request):
	request.session['vipUser'] = ""
	request.session['username'] = ""
	return HttpResponse("<script>alert('退出');location.href='"+reverse('myhome_login')+"'</script>")		

			
		

# 注册
def register(request):
	import random
	if request.method == "GET":
		return render(request,'myhome/register.html')
	else:
		res = request.POST.dict()
		# 验证验证码
		codePhone = request.session.get('msgcode')['phone']
		code = request.session.get('msgcode')['code']
		if codePhone == res['phone']:
			if code == res['code']:
				pass
			else:
				return HttpResponse("<script>alert('验证码错误!');location.href='"+reverse('myhome_register')+"'</script>")
		else:
			return HttpResponse("<script>alert('手机不匹配!');location.href='"+reverse('myhome_register')+"'</script>")
		
		user = models.Users()
		user.phone = res['phone']
		# 随机生成一个用户名
		user.username = "用户"+str(random.randint(1,100000000000))
		# 加密

		user.password = getPwd(res['password'])
		# 添加一个默认头像
		user.pic_url='/static/myadmin/img/default.jpg'
		user.email = res['email']
		user.save()
		return HttpResponse("<script>alert('注册成功!');location.href='"+reverse('myhome_login')+"'</script>")

# ajax判断用户名存不存在与数据库
def ajaxUser(request):
	phone = request.GET.get('phone')
	try:
		res = models.Users.objects.get(phone=phone)
		return HttpResponse(json.dumps({"error":1,"msg":"用户名已存在"}))
	except:
		return HttpResponse(json.dumps({"error":0,"msg":"用户名不存在可以登录"}))


# 手机短信验证码发送
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C70979167" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "f1567024d388f54c1a1dc71a8be123b4"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    print(code)
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    # text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # # 发起 请求
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # # 获取响应内容
    # content =req.read()
    # # 解析结果
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')


# 验证码测试页面
def yanzhengma(request):

	return render(request,'myhome/yanzhengma.html')

